#include <time.h>       // 生成时间戳
#include <fcntl.h>      // 提供文件控制选项
#include <stdio.h>      // 标准输入输出
#include <stdlib.h>     // 动态内存分配
#include <string.h>     // 字符串操作
#include <ctype.h>      // 字符类型判断
#include <unistd.h>     // 文件/网络操作
#include <stdarg.h>     // 日志可变参数
#include <arpa/inet.h>  // 网络地址转换
#include <sys/socket.h> // 网络套接字
#include <sys/select.h> // IO多路复用

// ============== 说明 ==============
// 已完成：增加配置文件
// 下一步：增加ADC 

// ============== 宏定义 ==============
// 详见配置文件
//#define PORT            9080
//#define BUF_SIZE        4096
//#define MAX_CLIENTS     10
//#define LOGIN_LOG        "receive_massages.log"

int PORT;
int BUF_SIZE;
int MAX_CLIENTS;

//char PORT[64];
char LOGIN_LOG[64];
char DEBUG_LOG[64];
char INFO_LOG[64];
char ERROR_LOG[64];

// ============== 宏函数 ==============
#define LOG_ERR(cond, msg, cleanup) \
    do { \
        if (cond) { \
            write_server_log(ERROR, "[%s:%d] %s", \
                             __FILE__, __LINE__, msg); \
            cleanup; \
            return -1; \
        } \
    } while(0)

#define LOG_INFO(fmt, ...) \
    do { \
        write_server_log(INFO, "[%s:%d] " fmt, \
                       __FILE__, __LINE__, ##__VA_ARGS__); \
    } while(0)

#define LOG_DEBUG(fmt, ...) \
    do { \
        write_server_log(DEBUG, "[%s:%d] " fmt, \
                       __FILE__, __LINE__, ##__VA_ARGS__); \
    } while(0)
// ============== 结构体 ==============
typedef struct conn_s{                  // 用于超时踢出
    int client_fd;
    time_t last_time;
}conn_s;

enum LogLevel { DEBUG, INFO, ERROR };   // 用于区分日志等级
                                        // ============== 函数声明 ==============
                                        // 服务器回复报文
int send_http_hello(int fd);            // 预留给stm32专用的废话报文
int send_http_response(int fd, const char* content_type, const char *content);

// 服务器获得id与移除用户
int get_device_id_from_request(const char *http_request);
void remove_client(fd_set *base_set, struct conn_s *client_fds, int *n_clients, int index);

// 服务器写日志
int write_stm32_log(int fd, const char *buf, int len);
int send_stm32_log(int client_fd);
int clear_stm32_log(int client_fd);
int write_server_log(enum LogLevel level, const char *format, ...);

// 服务器解析配置文件
void load_config(void);
int get_str_parameter(const char* key, char* value);
int get_num_parameter(const char* key, int* value);
static void trim_whitespace(char *str);
// ============== 主函数 ==============
int main() {
    // 加载配置文件
    load_config();
//    LOG_DEBUG("port = %d, MAX_CLIENTS = %d, BUF_SIZE = %d", PORT, MAX_CLIENTS, BUF_SIZE);

    // 检查句柄返回
    int ret_check = 0;

    // 创建socket
    int socket_fd = socket(AF_INET, SOCK_STREAM, 0);
    LOG_ERR(socket_fd < 0, "socket", NULL);

    // 设置端口复用
    int reuse = 1;
    ret_check = setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse));
    LOG_ERR(ret_check < 0, "setsockopt", close(socket_fd));

    // 绑定地址
    struct sockaddr_in addr = {
        .sin_family = AF_INET,
        .sin_port = htons(PORT),
        .sin_addr.s_addr = INADDR_ANY
    };

    ret_check = bind(socket_fd, (struct sockaddr*)&addr, sizeof(addr));
    LOG_ERR(ret_check < 0, "bind", close(socket_fd));

    // 开始监听
    ret_check = listen(socket_fd, MAX_CLIENTS);  // [!] 使用宏定义
    LOG_ERR(ret_check < 0, "listen", close(socket_fd));

    LOG_INFO("Server started on port %d\n", PORT);
    //write_server_log(INFO, "Server started on port %d\n", PORT);

    // 创建监听队列
    conn_s client_fds[MAX_CLIENTS];
    memset(client_fds, 0, sizeof(client_fds));
    int n_clients = 0;

    // base_set，保存下一次循环要监听的文件描述符集合
    fd_set base_set;
    FD_ZERO(&base_set);
    FD_SET(socket_fd, &base_set);
    FD_SET(STDIN_FILENO, &base_set);

    while (1) {
        // 1. 准备工作：更新下标 | 监听 | 超时踢出
        fd_set read_set;
        FD_ZERO(&read_set);
        memcpy(&read_set, &base_set, sizeof(base_set));

        int max_fd = socket_fd;
        for(int i = 0; i < n_clients; i++){
            if(client_fds[i].client_fd > max_fd){
                max_fd = client_fds[i].client_fd;
            }
        }

        struct timeval tv;
        tv.tv_sec = 10;     // 误差为10秒
        tv.tv_usec = 0;
        ret_check = select(max_fd + 1, &read_set, NULL, NULL, &tv);
        LOG_ERR(ret_check < 0, "select", NULL);

        // 2. 处理新链接, accept并添加到client_fds
        if(FD_ISSET(socket_fd, &read_set)){
            // 接受客户端连接
            struct sockaddr_in client_addr;
            socklen_t addr_len = sizeof(client_addr);

            // 监听到新链接
            int new_fd = accept(socket_fd, (struct sockaddr*)&client_addr, &addr_len);

            // 将新链接加入监听，并保存net_fd到list
            if(new_fd < 0){
                //write_server_log(INFO, "accept failed\n");
                LOG_INFO("accept failed\n");
            }
            else if(n_clients < MAX_CLIENTS){
                //write_server_log(INFO, "New client from %s:%d (fd=%d)\n", inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port), new_fd);
                LOG_INFO("New client from %s:%d (fd=%d)\n", inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port), new_fd);

                FD_SET(new_fd, &base_set);
                client_fds[n_clients].client_fd = new_fd;
                time(&client_fds[n_clients].last_time);
                n_clients++;
            }
            else{
                close(new_fd);
                //write_server_log(INFO, "Max clients reached!\n");
                LOG_INFO("Max clients reached!\n");
            }
        }

        // 3. 处理客户端消息
        for(int i = 0; i < n_clients; i++){
            if (FD_ISSET(client_fds[i].client_fd, &read_set)) {
                char buf[BUF_SIZE];
                ssize_t len = recv(client_fds[i].client_fd, buf, sizeof(buf) - 1, 0); // 保留空间给'\0'

                // 3.1 用户已断开链接
                if (len <= 0) {
                    //write_server_log(INFO, "Client %d disconnected\n", client_fds[i].client_fd);
                    LOG_INFO("Client %d disconnected\n", client_fds[i].client_fd);
                    
                    remove_client(&base_set, client_fds, &n_clients, i);
                    i--;
                }
                // 3.2 写文件并回复
                else{
                    buf[len] = '\0';
                    //write_server_log(INFO, "From client[fd=%d]:\n%.*s\n", client_fds[i].client_fd, (int)len, buf);
                    LOG_INFO("From client[fd=%d]:\n%.*s\n", client_fds[i].client_fd, (int)len, buf);

                    // 3.2.1 将收到的内容写到文件
                    int file_fd = open("receive_massages.log", O_WRONLY | O_CREAT | O_APPEND, 0644);
                    if(file_fd >= 0){
                        LOG_INFO("%s", buf);
                        // write_server_log(INFO, buf);
                        if(get_device_id_from_request(buf) == 0){
                            ret_check = write_stm32_log(file_fd, buf, len);
                            LOG_ERR(ret_check < 0, "Failed to write_log_entry", NULL);
                            close(file_fd);
                        }

                        time(&client_fds[i].last_time);
                    }
                    else{
                        perror("open log file failed");
                    }

                    // 3.2.2 回复报文
                    int dev_id = get_device_id_from_request(buf);
                    switch(dev_id) {
                    case 0: 
                        ret_check = send_http_response(client_fds[i].client_fd, "text/plain", "To STM32: Message received and logged");
                        LOG_ERR(ret_check < 0, "Fail to send_http_response", NULL);
                        break;
                    case 1:
                        ret_check = send_stm32_log(client_fds[i].client_fd);
                        LOG_ERR(ret_check < 0, "send_log failed", NULL);

                        remove_client(&base_set, client_fds, &n_clients, i);
                        i--;
                        break;
                    case 2:
                        ret_check = clear_stm32_log(client_fds[i].client_fd);
                        LOG_ERR(ret_check < 0, "send_log failed", NULL);

                        remove_client(&base_set, client_fds, &n_clients, i);
                        i--;
                        break;
                    default:
                        send_http_hello(client_fds[i].client_fd); 
                        break;
                    }
                }
            }
        }

        // 4. 遍历所有用户, 看是否超时
        time_t  now_time;
        time(&now_time);

        for(int i = 0; i < n_clients; i++){
            if(now_time - client_fds[i].last_time > 60){
                //write_server_log(INFO, "Client %d timed out (60s), kicking...\n", client_fds[i].client_fd);
                LOG_INFO("Client %d timed out (60s), kicking...\n", client_fds[i].client_fd);
                remove_client(&base_set, client_fds, &n_clients, i);
                i--;
            }
        }

    }

    // 5.会话结束，清理句柄
    for(int i = 0; i < n_clients; i++){
        if(client_fds[i].client_fd > 0){
            close(client_fds[i].client_fd);
        }
    }
    close(socket_fd);
    return 0;
}

// ============== 函数实现 ==============
int send_http_hello(int fd) {
    char body[BUF_SIZE];
    snprintf(body, sizeof(body),
             "HTTP/1.1 200 OK\r\n\r\n[\"Hello\"]\n");

    int ret_check = send(fd, body, strlen(body), 0);
    LOG_ERR(ret_check < 0, "Failed to send_http_hello", NULL);

    return 0;
}

int send_http_response(int fd, const char *content_type, const char *content) {
    char body[BUF_SIZE];
    snprintf(body, sizeof(body),
             "HTTP/1.1 200 OK\r\n\r\n%s\n", 
             content);

    int ret_check = send(fd, body, strlen(body), 0);
    LOG_ERR(ret_check < 0, "Failed to send_http_response", NULL);

    return 0;
}

int get_device_id_from_request(const char*http_request){
    // 1. 查找路径的位置
    const char *path_start = strstr(http_request, "GET /");
    if (!path_start) return -1;

    // 2. 定位数字位置
    const char* num_ptr = path_start + 5;   // "跳过GET /"
    if(!isdigit(*num_ptr)) return -1;

    // 3. 转换ASCII数字为整型
    return *num_ptr - '0';
}

void remove_client(fd_set *base_set, struct conn_s *client_fds, int *n_clients, int index) {
    printf("Removing client (fd=%d)\n", client_fds[index].client_fd);

    // 1. 从 select 监听集合移除
    FD_CLR(client_fds[index].client_fd, base_set);

    // 2. 关闭 socket
    close(client_fds[index].client_fd);

    // 3. 从数组移除（前移后续元素）
    for (int k = index; k < *n_clients - 1; k++) {
        client_fds[k] = client_fds[k + 1];
    }

    // 4. 更新客户端数量
    (*n_clients)--;
}

int write_stm32_log(int fd, const char *buf, int len){
    // 1. 生成时间戳
    char timestamp[64];
    time_t now = time(NULL);
    struct tm *tm_info = localtime(&now);
    strftime(timestamp, sizeof(timestamp), "[%Y-%m-%d %H:%M:%S]", tm_info);

    // 2. 过滤特殊字符（可选）
    char filtered[len + 1];
    for (int i = 0; i < len; i++) {
        filtered[i] = (buf[i] == '\r' || buf[i] == '\n') ? ' ' : buf[i];
    }
    filtered[len] = '\0';

    // 3. 写入文件
    dprintf(fd, "%s ", timestamp);             // 写入时间
    write(fd, filtered, len);                  // 写入内容
    write(fd, "\n", 1);                        // 换行

    return 0;

}

int send_stm32_log(int client_fd) {
    //    printf("[test] main.c send_log line274 | open normally\n");

    // 1. 打开文件
    FILE *file = fopen(LOGIN_LOG, "r");
    if (!file) {
        send_http_response(client_fd, "text/plain", "File error");
        return -1;
    }

    // 2. 准备缓冲区
    char total_buf[BUF_SIZE]; // JSON开始
    memset(total_buf, 0, sizeof(total_buf));
    strcpy(total_buf, "[");
    char line_buf[256];
    int line_count = 0;

    // 3. 读取文件
    while (fgets(line_buf, sizeof(line_buf), file)) {
        line_count++;
        //        printf("[TEST]main.c line309 |  正在处理第%d行: %s\n", line_count, line_buf);    
        if (strstr(line_buf, "GET /0")) {
            // 原始格式：[2025-05-30 23:09:05] [fd:4]GET /0 HTTP/1.1    [Buzzer:OFF]
            // 目标格式：[2025-05-30 23:09:05]     [Buzzer:OFF]

            // 1. 核心逻辑：提取第一对[]和最后一对[]
            char *first_bracket = strchr(line_buf, '[');
            char *first_end = strchr(line_buf, ']');

            char *last_bracket = strrchr(line_buf, '[');
            char *last_end = strrchr(line_buf, ']');

            // 2. 拼接时间戳 + "    " + Buzzer状态
            if (first_bracket && first_end && last_bracket && last_end) {
                //               printf("[test] main.c send_log line300 | enter strcmp normally\n");  

                // 计算两部分长度
                int first_len = first_end - first_bracket + 1;  // 包括[]
                int last_len = last_end - last_bracket + 1;      // 包括[]

                char temp[256];
                snprintf(temp, sizeof(temp), "\"%.*s    %.*s\"",
                         first_len, first_bracket,
                         last_len, last_bracket);

                //                printf("[test] main.c send_log line316 | finish strcmp normally, the temp is : %s\n", temp);
                // 3. 缓冲区检查
                if (strlen(total_buf) + strlen(temp) + 3 < sizeof(total_buf)) {
                    if (total_buf[1] != '\0') {  // 不是第一个元素（初始为"["）
                        strcat(total_buf, ",");
                    }
                    strcat(total_buf, temp);
                }
                else{
                    //                    printf("[test] main.c line345 | goto break\n");
                    break;
                }

                //                printf("[test] main.c send_log line336 | finish strcmp normally, the temp is : %s\n", temp);
                //                printf("[test] main.c send_log line337 | finish strcmp normally, the total_buf is : %s\n", total_buf);
            }
        }
    }
    // 4. 收尾并发送
    strcat(total_buf, "]");

    // 5. 发送（保持原方式）
    send_http_response(client_fd, "application/json", total_buf);
    fclose(file);
    //    printf("[test] main.c send_log line335 | close normally\n");
    return 0;
}

int clear_stm32_log(int client_fd){
    // 1. 打开文件
    int ret_check = truncate(LOGIN_LOG, 0);
    if(ret_check < 0){
        perror("Clear failed");
    }

    return 0;
}

int write_server_log(enum LogLevel level, const char *format, ...){
    // 1. 打开日志文件（静态变量避免重复打开）
    static int debug_log_fd = -1;
    static int info_log_fd = -1;
    static int error_log_fd = -1;

    if (debug_log_fd < 0) {
        debug_log_fd = open("server_debug.log", O_WRONLY | O_CREAT | O_APPEND, 0644);
        info_log_fd = open("server_info.log", O_WRONLY | O_CREAT | O_APPEND, 0644);
        error_log_fd = open("server_error.log", O_WRONLY | O_CREAT | O_APPEND, 0644);
        if (debug_log_fd < 0 || info_log_fd < 0 || error_log_fd < 0) {
            perror("Failed to open log files");
            return -1;
        }
    }

    // 2. 生成时间戳
    char timestamp[64];
    time_t now = time(NULL);
    struct tm *tm_info = localtime(&now);
    strftime(timestamp, sizeof(timestamp), "[%Y-%m-%d %H:%M:%S]", tm_info);

    // 3. 写日记
    char message[256];
    va_list args;
    va_start(args, format);
    vsnprintf(message, sizeof(message), format, args);
    va_end(args);

    // 4. 过滤特殊字符
    char filtered[256];      // 存储过滤后的消息
    for (int i = 0; message[i] != '\0'; i++) {
        filtered[i] = (message[i] == '\r' || message[i] == '\n') ? ' ' : message[i];
    }
    filtered[strlen(message)] = '\0';  // 确保字符串终止

    // 5. 写入文件
    switch(level){
    case 2 :
        dprintf(error_log_fd, "%s [%s] %s\n", timestamp, (const char*[]){"DEBUG","INFO","ERROR"}[level], filtered);
    case 1 :
        dprintf(info_log_fd, "%s [%s] %s\n", timestamp, (const char*[]){"DEBUG","INFO","ERROR"}[level], filtered);
    case 0 :
        dprintf(debug_log_fd, "%s [%s] %s\n", timestamp, (const char*[]){"DEBUG","INFO","ERROR"}[level], filtered);
        break;
    }

    // 6. 输出到屏幕
    const char *level_str[] = {"DEBUG", "INFO", "ERROR"};
    printf("%s [%s]\n %s\n", timestamp, level_str[level], message);

    //    close(debug_log_fd);
    //    close(info_log_fd);
    //    close(error_log_fd);
    return 0;
}

void load_config(void){
    get_num_parameter("port", &PORT);
    get_num_parameter("BUF_SIZE", &BUF_SIZE);
    get_num_parameter("MAX_CLIENTS", &MAX_CLIENTS);
    
    //get_str_parameter("port", PORT);
    get_str_parameter("LOGIN_LOG", LOGIN_LOG);
    get_str_parameter("DEBUG_LOG", DEBUG_LOG);
    get_str_parameter("INFO_LOG", INFO_LOG);
    get_str_parameter("ERROR_LOG", ERROR_LOG);
}

int get_str_parameter(const char* key, char* value){
    FILE * file = fopen("config.ini", "r");
    if(!file) return -1;

    char line_buf[64];
    bzero(line_buf, sizeof(line_buf));
    while(1){                            
        // 读一行数据
        char *res = fgets(line_buf, sizeof(line_buf), file);
        if(res == NULL){
            char buf[] = "没有要找的内容 \n";
            memcpy(value, buf, strlen(buf));
            return -1;
        }

        // 取出空格，跳过注释
        trim_whitespace(line_buf);
        if (line_buf[0] == '#' || line_buf[0] == '\0') continue;  // 跳过注释和空行

        // 处理数据
        char *line_key = strtok(line_buf, "=");
        if(strcmp(key, line_key) == 0){
            // 要找的内容
            char *line_value = strtok(NULL, "\n"); // 取剩余部分
            memcpy(value, line_value, strlen(line_value));
            fclose(file);
            return 0;
        }
    }

    fclose(file);
    return -1; // 未找到配置项
}

int get_num_parameter(const char* key, int* value){
    FILE *file = fopen("config.ini", "r");
    if (!file) return -1;

    char line_buf[64];
    while (fgets(line_buf, sizeof(line_buf), file)) {
        trim_whitespace(line_buf);
        if (line_buf[0] == '#' || line_buf[0] == '\0') continue;

        // 分割键值对（如 "port = 9080"）
        char *line_key = strtok(line_buf, "=");
        
        //LOG_DEBUG("line_key = %s", line_key);
        //LOG_DEBUG("key = %s", key);
        
        if (strncmp(key, line_key, strlen(key)) == 0) {
            char *line_value = strtok(NULL, "\n"); // 取剩余部分
            
            //LOG_DEBUG("line_value = %s", line_value);

            if (line_value) {
                * value = atoi(line_value); // 字符串转int
                
                //LOG_DEBUG("value = %d", value);
                //LOG_DEBUG("*value = %d", *value);

                fclose(file);
                return 0;
            }
        }
    }

    fclose(file);
    return -1; // 未找到配置项
}

static void trim_whitespace(char *str) {
    char *end;
    while (isspace((unsigned char)*str)) str++;  // 跳过头部空格
    end = str + strlen(str) - 1;
    while (end > str && isspace((unsigned char)*end)) end--;  // 跳过尾部空格
    *(end + 1) = '\0';
}
